package com.jsoft.jsofted.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jsoft.jsofted.platform.entity.MenuEntity;
import com.jsoft.jsofted.platform.mapper.MenuMapper;
import com.jsoft.jsofted.framework.mybatis.CocQueryWrapper;
import com.jsoft.jsofted.framework.service.impl.CocServiceImpl;
import com.jsoft.jsofted.platform.service.MenuService;
import com.jsoft.jsofted.platform.vo.MenuBean;
import com.jsoft.jsofted.platform.vo.MenuTreeMaker;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Service
public class MenuServiceImpl extends CocServiceImpl<MenuMapper, MenuEntity> implements MenuService {
    @Override
    public List<MenuBean> queryTree(Map queryParams) {
        if (queryParams == null) {
            queryParams = new LinkedHashMap();
        }

        CocQueryWrapper queryWrapper = new CocQueryWrapper();
        this._parseSortParams(queryWrapper, queryParams);
        this._parseKeywordsParams(queryWrapper, queryParams);
        this._parseRoleParams(queryWrapper, queryParams);

        List list = list(queryWrapper);
        List tree = MenuTreeMaker.make(list);

        return tree;
    }

    /**
     * 解析【条件参数】中的【角色参数】
     * 查询角色可以访问哪些功能菜单？
     */
    private void _parseRoleParams(CocQueryWrapper queryWrapper, Map queryParams) {
        String roleId = (String) queryParams.get("roleId");
        if (StringUtils.hasText(roleId)) {
            queryWrapper.subSelect("id", "in",
                    "(select menu_id from sys_role_perm where role_id = {0})", roleId);
        }
    }

    private void _parseSortParams(CocQueryWrapper queryWrapper, Map queryParams) {
        queryWrapper.orderByDesc("sort_value", "create_time");
    }

    /**
     * 解析【条件参数】中的【关键字参数】
     */
    private void _parseKeywordsParams(CocQueryWrapper queryWrapper, Map condParams) {
        String keywords = (String) condParams.get("keywords");
        if (keywords == null || keywords.trim().length() == 0) {
            return;
        }

        Consumer<CocQueryWrapper> consumer = qw -> {
            qw.like("name", keywords);
            qw.or();
            qw.like("path", keywords);
            qw.or();
            qw.like("page", keywords);
        };
        queryWrapper.and(consumer);
    }

    @Override
    public List<MenuEntity> queryMenusByUser(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("sort_value", "create_time");
        // TODO: 查询条件待完善
        return this.list(queryWrapper);
    }
}
